package com.klhappy.houyuan.activity;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import com.klhappy.houyuan.R;
import com.klhappy.houyuan.adapter.OrderItemAdapter;
import com.klhappy.houyuan.bean.BaseJsonBean;
import com.klhappy.houyuan.bean.EvaluateBean;
import com.klhappy.houyuan.bean.EvaluateOrder.ItemEvaBean;
import com.klhappy.houyuan.bean.EvaluateOrder.OrderJsonBean;
import com.klhappy.houyuan.constant.KeyConstant;
import com.klhappy.houyuan.constant.UrlConstant;
import com.klhappy.houyuan.interfaces.CallBackInterModle;
import com.klhappy.houyuan.modle.DingDanModle;
import com.klhappy.houyuan.utils.EvaluateDeal;
import com.klhappy.houyuan.utils.NotifyMethod;
import com.klhappy.houyuan.utils.imageselector.Bimp;
import com.klhappy.houyuan.utils.imageselector.FileUtils;
import com.klhappy.houyuan.utils.imageselector.ImageItem;
import com.klhappy.houyuan.view.AbsActivity;
import com.klhappy.houyuan.view.WholeListView;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class RatingActivity extends AbsActivity implements CallBackInterModle {
    private static final int REQUEST_CODE_TAKE_PICTURE = 18;
    public static final String AVG = "RatingActivity";
    public static final String REMOVE = "remove";
    public static final String CALL = "call";
    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.lv_goods)
    WholeListView lvGoods;
    @InjectView(R.id.freshBar)
    RatingBar freshBar;
    @InjectView(R.id.serviceBar)
    RatingBar serviceBar;
    @InjectView(R.id.speedBar)
    RatingBar speedBar;
    @InjectView(R.id.tv_evaluation)
    EditText tv_evaluation;

    @OnClick(R.id.click_ra)
    public void click_ra() {
        finish();
    }

    @OnClick(R.id.btn_confirm)
    public void btn_confirm() {
        if (!TextUtils.isEmpty(count)) {
            showToastx("请填写交易评价");
        } else {
            showDialog("上传中...");
            modle.setEvaluate(setnformation());
        }
    }

    private DingDanModle modle;
    private OrderJsonBean jsonBean;
    private String or_id;
    private String count;
    private OrderItemAdapter itemAdapter;
    private List<ItemEvaBean> lists;

    public static Bitmap bimap;

    private String filePath = "";
    private String fileName = "";
    private File file_sdcard;
    private File mHeadShotDir;
    private int num;
    private EvaluateDeal deal;
    private boolean isCall = false;
    private File[] files;
    private ArrayList<EvaluateBean.OrderDetail> orderDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rating);
        ButterKnife.inject(this);
        title.setText("评价订单");
        modle = new DingDanModle(this);
        modle.setCallBackInterModle(this);

        Bimp.max = 0;
        Bimp.selectBitmap.clear();
        bimap = BitmapFactory.decodeResource(getResources(),
                R.drawable.add_picture_img);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        orderDetail = (ArrayList<EvaluateBean.OrderDetail>) getIntent().getSerializableExtra("goods");
        or_id = (String) getIntent().getSerializableExtra("or_id");

        for (int i = 0; i < orderDetail.size(); i++) {
            Bimp.allListBitmap.add(new ArrayList<ImageItem>());
        }

        itemAdapter = new OrderItemAdapter(this, orderDetail, dm);
        lvGoods.setAdapter(itemAdapter);

        NotifyMethod.getInstance().addObserver(AVG, new NotifyMethod.NotifyListener() {
            @Override
            public void notify(Object o) {
                photo();
            }
        });
        NotifyMethod.getInstance().addObserver(REMOVE, new NotifyMethod.NotifyListener() {
            @Override
            public void notify(Object o) {
                showDialog("请稍等...");
                num = (int) o;
                modle.remove(deal.name.get(num));
            }
        });
        NotifyMethod.getInstance().addObserver(CALL, new NotifyMethod.NotifyListener() {
            @Override
            public void notify(Object o) {
                setIdea();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isCall) {
            itemAdapter.Notif();
        }
        isCall = true;
    }

    @Override
    public void CallBackFromModle(String url, BaseJsonBean o) {
        if (url.equals(UrlConstant.COMMENT_URL)) {
            if (o.getCode() == 200) {
                showToast(o.getMsg());
                finish();
                Bimp.allListBitmap.clear();
            }
            closeDialog();
        } else if (url.equals(UrlConstant.QINGCHU)) {
            if (o.getCode() == 200) {
                itemAdapter.Notif();
            }
            showToastx(o.getMsg());
            closeDialog();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Bimp.allListBitmap.get(itemAdapter.getNum()).size() < 4 && requestCode == REQUEST_CODE_TAKE_PICTURE) {
            ImageItem takePhoto = new ImageItem();
            if (resultCode == RESULT_OK) {//拍照返回
                mConfigManage.remove("number");
                mConfigManage.set("number", Bimp.allListBitmap.get(itemAdapter.getNum()).size());
                takePhoto.setImagePath(filePath + File.separator + fileName);
                takePhoto.setName(fileName);
                Bimp.allListBitmap.get(itemAdapter.getNum()).add(takePhoto);
                fileName = "";
            }
            setIdea();
        }
    }

    public void photo() {
        if ("".equals(filePath)) {
            filePath = FileUtils.getImagePath(this);
        }
        initImageFileCache();
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        String date = sDateFormat.format(new java.util.Date());
        int num = (int) (Math.random() * 100);
        fileName = date + num + ".jpg";
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filePath, fileName)));
        startActivityForResult(openCameraIntent, REQUEST_CODE_TAKE_PICTURE);
    }

    private OrderJsonBean setnformation() {
        jsonBean = new OrderJsonBean();

        String id = or_id;
        count = tv_evaluation.getText().toString() + "";
        String fresh = freshBar.getNumStars() + "";
        String service = serviceBar.getNumStars() + "";
        String speed = speedBar.getNumStars() + "";

        lists = itemAdapter.getLists();
        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        for (int i = 0; i < orderDetail.size(); i++) {
            JSONObject item = new JSONObject();
            try {
                item.put("goods_id", orderDetail.get(i).getGoods_id());
                item.put("content", lists.get(i).getCount());
                item.put("fresh_gre", lists.get(i).getRating());
                item.put("rec_id", orderDetail.get(i).getRec_id());
                array.put(item);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        try {
            object.put("comments", array);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonBean.ToJsonBean(id, count, fresh, service, speed, object);
        return jsonBean;
    }

    //创建文件夹
    private void initImageFileCache() {
        file_sdcard = Environment.getExternalStorageDirectory();
        mHeadShotDir = new File(file_sdcard, KeyConstant.APP_DIR
                + File.separator + KeyConstant.IMAGE_DIR + File.separator
                + KeyConstant.HEAD_SHOT);
        if (!mHeadShotDir.exists()) {
            mHeadShotDir.mkdirs();
        }
    }

    //意见反馈
    public void setIdea() {
        Log.e("this", "sssssss" + Bimp.allListBitmap.toString());
        int agoNum = mConfigManage.get("number", 0);
        int nowNum = Bimp.allListBitmap.get(itemAdapter.getNum()).size();
        files = new File[nowNum - agoNum];
        int place = 0;
        for (int i = 0; i < nowNum; i++) {
            if (i >= agoNum) {
                files[place] = new File(Bimp.allListBitmap.get(itemAdapter.getNum()).get(i).getImagePath());
                place++;
            }
        }
        String rec_id = orderDetail.get(itemAdapter.getNum()).getRec_id();
        deal = new EvaluateDeal(this, rec_id);
        deal.dealPicture(files);
    }
}
